package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;

public class CountAndSay {

    /**
     * 循环生成
     * @param n
     * 1 <= n <= 30
     */
    public String countAndSay1(int n) {
        String pre = "1";
        for (int i = 1; i < n; ++i){
            int count = 1;
            char preChar = pre.charAt(0);
            StringBuilder sb = new StringBuilder();
            for (int k = 1; k < pre.length(); ++k){
                if (pre.charAt(k) == preChar){
                    count++;
                } else {
                    sb.append(count).append(preChar);
                    preChar = pre.charAt(k);
                    count = 1;
                }
            }
            sb.append(count).append(preChar);
            pre = sb.toString();
        }
        return pre;
    }

    /**
     * 递归
     */
    public String countAndSay(int n) {
        if (n == 1){
            return "1";
        }
        int count = 1;
        String pre = countAndSay(n - 1);
        char preChar = pre.charAt(0);
        StringBuilder sb = new StringBuilder();
        for (int k = 1; k < pre.length(); ++k){
            if (pre.charAt(k) == preChar){
                count++;
            } else {
                sb.append(count).append(preChar);
                preChar = pre.charAt(k);
                count = 1;
            }
        }
        sb.append(count).append(preChar);
        pre = sb.toString();
        return pre;
    }

    public static void main(String[] args) {
        int n = 4;
        String res = new CountAndSay().countAndSay(n);
        System.out.println(res);
        Assert.isTrue(res.equals("1211"));
    }
}
